package site;

import constans.SizeConstans;
import database.ConnectionDB;
import database.DatabaseMysql;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;


public class ListRequest extends ProcessRequest {

    private final int windowSize = 40;
    private final String databaseHost;
    private final String databaseName;
    private final String databasePassword;
    private final String databaseUser;



    public ListRequest(ServletContext context){
        databaseHost      = context.getInitParameter("DatabaseHost");
        databaseName      = context.getInitParameter("DatabaseName");
        databasePassword  = context.getInitParameter("DatabasePassword");
        databaseUser      = context.getInitParameter("DatabaseUser");
    }

    @Override
    protected void process(HttpServletResponse response, String[] arguments) {

        response.setContentType("text/html; charset=\"UTF-8\"");

        PrintWriter out = null;
        ConnectionDB connectionDB =null;
        DecimalFormat df = new DecimalFormat("#.#");                             


        try {

            out=  response.getWriter();

            connectionDB =  new DatabaseMysql(databaseHost,databaseUser,databasePassword ,databaseName).getConnection();

            String language = arguments[0];//Get language
            
            int offset;
            try{
                   if( (offset = Integer.parseInt(arguments[1]))<0)//Get offset
                    offset = 0;
             } catch(NumberFormatException e){
                    offset = 0;
             }

            String query = "SELECT User.name, User.initDate, Identifier.offeredSpace " +
                    "FROM User, Identifier " +
                    "WHERE User.email = Identifier.email AND Identifier.offeredSpace > 0 AND Identifier.lastUpdate > (SELECT DATE_SUB(curdate(), INTERVAL 1 MONTH)) " +
                    "ORDER BY Identifier.offeredSpace DESC limit "+windowSize+" offset "+(offset*windowSize);
            
            ResultSet rs = connectionDB.executeSelect(query);

            out.println("<HTML>");
            out.println("<HEAD>");
            out.println("<META http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"><a href=\"http://www.arquivo.pt\"><img src=\"http://arquivo-web.fccn.pt/logo.jpg\" alt=\"Logotipo AWP\" border=\"0\"></a>");
            out.println("<META http-equiv=\"content-language\" content=\""+language+"\">");

            if(language.equals("en")){
               out.println("<META name=\"description\" content=\"List of the rARC contributors.\">");
               out.println("<META name=\"keywords\" content=\"rARC, list, contributors\">");
               out.println("<TITLE>List of rARC contributors</TITLE>");
            }
            else{
               out.println("<META name=\"description\" content=\"Lista dos contribuidores do rARC.\">");
               out.println("<META name=\"keywords\" content=\"rARC, lista, contribuidores\">");
               out.println("<TITLE>Lista dos contribuidores do rARC</TITLE>");
            }

            out.println("</HEAD><BODY>");

             if(language.equals("en")){
                out.println("<CENTER><H1>List of rARC contributors</H1></CENTER>");
                out.println("This table shows the rARC contributors. This table is ordered in descending order of disk space.<p>");
             }
            else{
                out.println("<CENTER><H1>Lista dos contribuidores do rARC</H1></CENTER>");
                out.println("A seguinte tabela apresenta os contribuidores do rARC. A tabela está ordenada por ordem decrescente de espaço oferecido.<p>");
            }

            rs.last();

            int totalCount= rs.getRow();
            String next, prev;

            if(language.equals("en")){
                next ="Next";
                prev ="Previous";
            }else{
                next ="Próximos";
                prev ="Anteriores";
            }

            if(offset==0 && totalCount >= windowSize)
            {
                out.println("<a href=\"http://arquivo-web.fccn.pt/rarc/show/list/?l="+language+"&o="+(offset+1)+"\">"+next+" "+windowSize+"</a>");
            }
            else if(offset>0 && totalCount  == windowSize)
            {
                out.println("<a href=\"http://arquivo-web.fccn.pt/rarc/show/list/?l="+language+"&o="+(offset-1)+"\">"+prev+" "+windowSize+"</a> | ");
                out.println("<a href=\"http://arquivo-web.fccn.pt/rarc/show/list/?l="+language+"&o="+(offset+1)+"\">"+next+" "+windowSize+"</a>");
            }
            else if(offset>0 && totalCount <  windowSize )
            {
                 out.println("<a href=\"http://arquivo-web.fccn.pt/rarc/show/list/?l="+language+"&o="+(offset-1)+"\">"+prev+" "+windowSize+"</a> ");
            }

            out.println("<HR SIZE=1>");
            out.println("<TABLE BORDER=1 WIDTH =\"100%\">");

             if(language.equals("en"))
                out.println("<tr><th>Rank</th><th>Name</th><th>Contributor since</th><th>Offered space</th></tr>");
             else
                 out.println("<tr><th>Posição</th><th>Nome</th><th>Contribuidor desde</th><th>Espaço oferecido</th></tr>");

            int total = (offset == 0 ? 1 : (offset*windowSize)+1);

            rs.beforeFirst();

            while(rs.next()){

                out.println("<tr>");
                out.println("<td align=center>"+total+"</td>");
                out.println("<td align=center>"+rs.getString(1)+"</td>");//name
                out.println("<td align=center>"+rs.getDate(2).toString()+"</td>");//participant since
                out.println("<td align=center>"+df.format(rs.getDouble(3)/SizeConstans.GByte)+" GB</td>");//offered space
                out.println("</tr>");

                total++;
            }

            out.println("</TABLE></CENTER>");
            out.println("<HR SIZE=1>");

            if(offset==0 && totalCount >= windowSize)
            {
                out.println("<a href=\"http://arquivo-web.fccn.pt/rarc/show/list/?l="+language+"&o="+(offset+1)+"\">"+next+" "+windowSize+"</a>");
            }
            else if(offset>0 && totalCount  == windowSize)
            {
                out.println("<a href=\"http://arquivo-web.fccn.pt/rarc/show/list/?l="+language+"&o="+(offset-1)+"\">"+prev+" "+windowSize+"</a> | ");
                out.println("<a href=\"http://arquivo-web.fccn.pt/rarc/show/list/?l="+language+"&o="+(offset+1)+"\">"+next+" "+windowSize+"</a>");
            }
            else if(offset>0 && totalCount <  windowSize )
            {
                 out.println("<a href=\"http://arquivo-web.fccn.pt/rarc/show/list/?l="+language+"&o="+(offset-1)+"\">"+prev+" "+windowSize+"</a> ");
            }

            out.println("</BODY></HTML>");
            out.flush();
            out.close();

        } catch (SQLException ex) {
            Logger.getLogger(ListRequest.class.getName()).log(Level.SEVERE, null, ex);
        }  catch (IOException ex) {
            Logger.getLogger(ListRequest.class.getName()).log(Level.WARNING, null, ex);
        } finally{
            if(out!=null){
                   out.close();
            }
            if(connectionDB!=null){
                try {
                    connectionDB.close();
                } catch (SQLException ex) {}
            }
        }

    }

}
